package org.fengling.readingplatform.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.fengling.readingplatform.manager.mapper.SysRoleMapper;
import org.fengling.readingplatform.manager.service.SysUserService;
import org.fengling.readingplatform.common.exception.FenglingException;
import org.fengling.readingplatform.manager.mapper.SysRoleUserMapper;
import org.fengling.readingplatform.model.dto.system.AssignRoleDto;
import org.fengling.readingplatform.model.dto.system.LoginDto;
import org.fengling.readingplatform.model.dto.system.SysUserDto;
import org.fengling.readingplatform.model.entity.system.SysRole;
import org.fengling.readingplatform.model.entity.system.SysUser;
import org.fengling.readingplatform.model.vo.common.ResultCodeEnum;
import org.fengling.readingplatform.model.vo.system.LoginVo;
import org.fengling.readingplatform.manager.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //用户登录
    @Override
    public LoginVo login(LoginDto loginDto){
        List<SysRole> roleList = sysRoleMapper.findAll();

        //1 获取输入验证码和存储到redis的key名称 LoginDto获取到
        String captcha = loginDto.getCaptcha();
        String key = loginDto.getCodeKey();

        //2 根据获取的redis里面的key，查询redis里面存储验证码
        String redisCode = redisTemplate.opsForValue().get("user:validate" + key);

        System.out.println("gg");
        //3 比较输入的验证码和redis存储验证码是否一致
        //4 如果不一致，提示用户，校验失败
        if(StrUtil.isEmpty(redisCode) || !StrUtil.equalsIgnoreCase(redisCode,captcha)){
            throw new FenglingException(ResultCodeEnum.VALIDATECODE_ERROR);
        }
        //5 如果一致，删除redis里面验证码
        redisTemplate.delete("user:validate" + key);

        //1 获取提交用户名，LoginDto获取到
        String userName = loginDto.getUserName();
        System.out.println(userName);

        //2 根据用户名查询数据库表sys_user表
        SysUser sysUser = sysUserMapper.selectUserInfoByUserName(userName);
        System.out.println(userName);

        //3 如果根据用户名查不到对应信息，用户不存在，返回错误信息
        if(sysUser == null){
            throw new FenglingException(ResultCodeEnum.LOGIN_ERROR);
        }

        //4 如果根据用户名查询到用户信息，用户存在
        //5 获取输入的密码，比较输入的密码和数据库密码是否一致
        String database_password = sysUser.getPassword();
        String input_password = loginDto.getPassword();

        if(!input_password.equals(database_password)){
            throw new FenglingException(ResultCodeEnum.LOGIN_ERROR);
        }

        //6 如果密码一致，登录成功，如果密码不一致则登录失败
        //7 登录成功，生成唯一表示token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        System.out.println(token);
        //8 把登录成功用户信息放到redis里面
        //key： token   value: 用户信息
        redisTemplate.opsForValue().set("user:login"+token, JSON.toJSONString(sysUser),7, TimeUnit.DAYS);

        //9 返回LoginVo对象
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        return loginVo;
    }

    //用户退出
    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login" + token);
    }

    //用户条件分页查询
    @Override
    public PageInfo<SysUser> findByPage(Integer pageNum, Integer pageSize, SysUserDto sysUserDto) {
        PageHelper.startPage(pageNum,pageSize);
        List<SysUser> list = sysUserMapper.findByPage(sysUserDto);
        PageInfo<SysUser> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    //用户删除
    @Override
    public void deleteById(Long userId) {
        sysUserMapper.delete(userId);
    }

    //用户分配角色
    @Override
    public void doAssign(AssignRoleDto assignRoleDto) {
        //1 根据userId删除用户之前分配角色数据
        sysRoleUserMapper.deleteByUserId(assignRoleDto.getUserId());

        //2 重新分配新数据
        List<Long> roleIdList = assignRoleDto.getRoleIdList();

        //遍历得到每个角色id
        for(Long roleId:roleIdList){
            sysRoleUserMapper.doAssign(assignRoleDto.getUserId(),roleId);
        }
    }
}

